package com.vay.de.dang.online.web;

import android.text.TextUtils;
import android.util.Log;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.entiy.BuriedPointEntity;
import com.vay.de.dang.online.entiy.CustomerEntity;
import com.vay.de.dang.online.phone.DeviceHelper;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.VnExecutors;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseApi {

    private static OkHttpClient httpClient;

    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30 * 60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(chain -> {

                    Request request = chain.request();
                    VnContext vnContext = VnContext.instance();

                    String appName = "Vaydedang";
                    String appPackageName = "com.vay.de.dang.online";
                    String appVersion = "1.0.1";
                    String areaCode = "84";
                    String countryCode = vnContext.getCountryCode();
                    String language = vnContext.getLanguage();

                    // App Header
                    Request.Builder reqBuilder = request.newBuilder();
                    //reqBuilder.addHeader("appName", appName);
                    //reqBuilder.addHeader("appPackageName", appPackageName);
                    //reqBuilder.addHeader("appVersion", appVersion);
                    //reqBuilder.addHeader("areaCode", areaCode);
                    //reqBuilder.addHeader("countryCode", countryCode);
                    //reqBuilder.addHeader("language", language);

                    //将header参数以json格式传入key：JLfLWOdJ
                    //header_table["kkvKw"] = "appName"
                    //header_table["JRta"] = "appPackageName"
                    //header_table["LTtvXihk"] = "appVersion"
                    //header_table["pxQ"] = "areaCode"
                    //header_table["NIqJQ"] = "countryCode"
                    //header_table["lHqNOn"] = "language"
                    //header_table["ZTZKi"] = "token"

                    Map<String, String> map = new HashMap<>();
                    map.put("kkvKw", appName);
                    map.put("JRta", appPackageName);
                    map.put("LTtvXihk", appVersion);
                    map.put("pxQ", areaCode);
                    map.put("NIqJQ", countryCode);
                    map.put("lHqNOn", language);

                    // build new request
                    String token = vnContext.getToken();
                    if (!TextUtils.isEmpty(token)) {
                        //reqBuilder.addHeader("token", token);
                        map.put("ZTZKi", token);
                    } else {
                        map.put("ZTZKi", "");
                    }

                    String jsonStr = JsonUtil.objectToJson(map);
                    reqBuilder.addHeader("JLfLWOdJ", jsonStr);

                    String str = "\nappName = " + appName;
                    str += "\nappPackageName = " + appPackageName;
                    str += "\nappVersion = " + appVersion;
                    str += "\nareaCode = " + areaCode;
                    str += "\ncountryCode = " + countryCode;
                    str += "\nlanguage = " + language;
                    str += "\ntoken = " + token;
                    log("~~~~~~~~~New Request~~~~~~~~~");
                    log("\n" + str);

                    return chain.proceed(reqBuilder.build());
                });

        httpClient = builder.build();
    }

    protected static String wrapperUrl(String path) {
        return "https://app.vaydedang.xyz/" + path;
        //return "http://test-vaydedang.greateamonline.com/" + path;
    }

    public static void log(String msg) {
        Log.d("VnApi", msg);
    }

    public static void execTask(WorkerBase worker) {
        VnExecutors.execTask(worker);
    }

    public static void execSingleTask(WorkerBase worker) {
        VnExecutors.execSingle(worker);
    }

    protected static String doGet(String url) throws Exception {
        return doGet(url, null);
    }

    private static String doGet(String url, Map<String, Object> header) throws Exception {
        Request.Builder builder = new Request.Builder();
        builder.url(url);

        // header
        if (header != null) {
            Set<String> keys = header.keySet();
            for (String key : keys) {
                Object value = header.get(key);
                builder.addHeader(key, (String) value);
            }
        }

        log("***************** Do GET ************************");
        log("Url: " + url);

        Response response = httpClient.newCall(builder.build()).execute();
        if (response.isSuccessful()) {
            if (response.body() != null) {
                String json = response.body().string();
                String info = "请求地址: " + url;
                info += "\n服务返回: " + json;
                log(info);
                return json;
            } else {
                return response.message();
            }
        } else {
            return response.message();
        }
    }

    protected static String doPostByJson(String url, String bodyJson) throws Exception {

        Request.Builder builder = new Request.Builder();
        builder.url(url);

        RequestBody requestBody = createPostJsonBody(bodyJson);
        builder.post(requestBody);

        log("***************** Do Post ************************");
        log("Url: " + url);
        log("Param: " + bodyJson);

        Response response = httpClient.newCall(builder.build()).execute();
        if (response.isSuccessful()) {
            if (response.body() != null) {
                String json = response.body().string();
                String info = "请求地址: " + url;
                info += "\n服务返回: " + json;
                log(info);
                return json;
            } else {
                return response.message();
            }
        } else {
            return response.message();
        }
    }

    protected static String doPostByBody(String url) throws Exception {
        return doPostByBody(url, "", null);
    }

    protected static String doPostByBody(String url, String body, Map<String, String> map) throws Exception {

        Request.Builder builder = new Request.Builder();
        builder.url(url);

        RequestBody requestBody;
        if (body == null || "".equals(body)) {
            requestBody = createPostStringBody(body);
        } else {
            requestBody = createPostFormData(map);
        }
        builder.post(requestBody);

        log("***************** Do Post ************************");
        log("Url: " + url);
        log("Body: " + body);

        Response response = httpClient.newCall(builder.build()).execute();
        if (response.isSuccessful()) {
            if (response.body() != null) {
                String json = response.body().string();
                String info = "请求地址: " + url;
                info += "\n服务返回: " + json;
                log(info);
                return json;
            } else {
                return response.message();
            }
        } else {
            return response.message();
        }
    }

    protected static String doPostFile(String url, File file) throws Exception {

        Request.Builder builder = new Request.Builder();
        builder.url(url);

        Map<String, File> map = new HashMap<>();
        map.put("file", file);
        RequestBody requestBody = createPostFileBody(map);
        builder.post(requestBody);

        log("***************** Post File ************************");
        log("Url: " + url);
        log("File: " + file.getAbsolutePath());

        Response response = httpClient.newCall(builder.build()).execute();
        if (response.isSuccessful()) {
            if (response.body() != null) {
                String json = response.body().string();
                String info = "请求地址: " + url;
                info += "\n服务返回: " + json;
                log(info);
                return json;
            } else {
                return response.message();
            }
        } else {
            return response.message();
        }
    }

    public static RequestBody createPostJsonBody(String body) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
    }

    public static RequestBody createPostStringBody(String body) {
        return RequestBody.create(MediaType.parse("text/x-www-form-urlencoded; charset=utf-8"), body);
    }

    public static RequestBody createPostFormData(Map<String, String> map) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (map != null) {
            Set<String> keys = map.keySet();
            for (String key : keys) {
                builder.addFormDataPart(key, map.get(key));
            }
        }
        return builder.build();
    }

    public static RequestBody createPostFileBody(Map<String, File> files) {
        MultipartBody.Builder builder = (new MultipartBody.Builder("AaB03x")).setType(MultipartBody.FORM);
        if (files != null && !files.isEmpty()) {
            Iterator var12 = files.keySet().iterator();
            while (var12.hasNext()) {
                String key = (String) var12.next();
                if (key != null && key.length() > 0) {
                    File file = files.get(key);
                    String fileName = file.getName();
                    builder.addFormDataPart(key, fileName, (new MultipartBody.Builder("BbC04y"))
                            .addPart(Headers.of(new String[]{"Content-Disposition", "form-data; filename=\"" + fileName + "\""}),
                                    RequestBody.create(MediaType.parse("image/png"), file)).build());
                }
            }
        }

        return builder.build();
    }

    // 获取验证码
    public static void sendCode(String phone, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() throws Exception {
                //String url = wrapperUrl("loanSupermarket/notauth/getVerificationCode/" + phone);
                String url = wrapperUrl("JQwwnvP/efCAet/jnmIlz/" + phone);
                String json = doGet(url);
                if (JsonUtil.isOk(json)) {
                    return ReqResult.ok("");
                } else {
                    return ReqResult.error(JsonUtil.readMsg(json));
                }
            }
        });
    }

    public static void queryServicePhone(ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    //String url = wrapperUrl("loanSupermarket/notauth/queryCustomerTelephone");
                    String url = wrapperUrl("ZKiapTTd/Omgh/DKsdXmG");
                    String json = doGet(url);
                    if (JsonUtil.isOk(json)) {
                        return ReqResult.ok(JsonUtil.toObjectByData(json, CustomerEntity.class));
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    // 基本信息
    public static void baseInfoRule(ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    //String url = wrapperUrl("wz/syscode/getCueRule");
                    String url = wrapperUrl("mVma/ZbG/ZyR");
                    String json = doGet(url);
                    if (JsonUtil.isOk(json)) {
                        return ReqResult.ok(JsonUtil.toPropertyRuleList(json));
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    // 证件规则
    public static void idTypeRule(ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    //String url = wrapperUrl("wz/syscode/getCueRuleIdType");
                    String url = wrapperUrl("UKLfyL/Fkdjj/jgnMnHFU");
                    String json = doGet(url);
                    if (JsonUtil.isOk(json)) {
                        return ReqResult.ok(JsonUtil.toPropertyRuleList(json));
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    public static String syncUploadFile(String path) {
        try {
            //String url = wrapperUrl("loanSupermarket/common/file/upload");
            String url = wrapperUrl("PinXTm/MdDARyby/BAjtPK/QIz");
            String json = doPostFile(url, new File(path));
            if (JsonUtil.isOk(json)) {
                return JsonUtil.readData(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 已经反馈
    public static void uploadFeedback(String content, List<String> path, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {

                    StringBuilder urls = new StringBuilder();
                    if (!VnUtil.isEmpty(path)) {
                        for (String u : path) {
                            String fileUrl = syncUploadFile(u);
                            if (!VnUtil.isEmpty(fileUrl)) {
                                if (urls.length() > 0) urls.append(",");
                                urls.append(fileUrl);
                            }
                        }
                    }

                    // # 165. 上传意见反馈-废弃
                    //【/loanSupermarket/my/upFeedback——>/egC/bZBSqiA/Iqjf】

                    // # 189. 上传意见反馈
                    //【/loanSupermarket/my/upFeedback/v1——>/ihWXNp/izsz/Muk/PvrLt】

                    Map<String, String> map = new HashMap<>();
                    map.put("feedbackContent", content);
                    map.put("feedbackPictures", urls.toString());
                    String str = JsonUtil.objectToJson(map);
                    //String url = wrapperUrl("loanSupermarket/my/upFeedback/v1");
                    String url = wrapperUrl("egC/bZBSqiA/Iqjf");
                    String json = doPostByJson(url, str);
                    if (JsonUtil.isOk(json)) {
                        return ReqResult.ok("");
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    protected static boolean isLocalFile(String path) {
        return path.startsWith("/data/");
    }

    public static BuriedPointEntity reqBuriedPoint(int pointCode, int pageCode, String pageName, String pointName) {
        BuriedPointEntity entity = new BuriedPointEntity();
        entity.setAndroidId(VnApp.getAfAndroidId());
        entity.setUuid(VnApp.getUuid());
        entity.setCustomerPhone(VnContext.instance().getPhone());
        entity.setDeviceModel(DeviceHelper.getDeviceModel());
        entity.setBuryingPointCode(pointCode);
        entity.setBuryingPointName(pointName);
        entity.setPageCode(pageCode);
        entity.setPageName(pageName);
        return entity;
    }

    public static void execBuriedPoint(int pointCode, int pageCode, String pageName, String pointName) {
        execBuriedPoint(pointCode, pageCode, pageName, pointName, "", 0);
    }

    public static void execBuriedPoint(int pointCode, int pageCode, String pageName, String pointName, String remark) {
        execBuriedPoint(pointCode, pageCode, pageName, pointName, remark, 0);
    }

    public static void execBuriedPoint(int pointCode, int pageCode, String pageName,
                                       String pointName, String remark, int eventTime) {
        BuriedPointEntity entity = reqBuriedPoint(pointCode, pageCode, pageName, pointName);
        entity.setEventTime(eventTime);
        entity.setBuryingPointRemark(remark);
        execBuriedPoint(entity);
    }

    public static void execBuriedPoint(BuriedPointEntity entity) {
        execBuriedPoint(entity, new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {

                }
            }
        });
    }

    // 埋点
    public static void execBuriedPoint(BuriedPointEntity entity, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    String param = JsonUtil.objectToJson(entity);
                    //String url = wrapperUrl("loanSupermarket/buriedpoint/notauth/execburiedpoint");
                    String url = wrapperUrl("bNbmZSS/NsClwY/YcV/oZzG");
                    String json = doPostByJson(url, param);
                    if (JsonUtil.isOk(json)) {
                        log("埋点执行成功: PageCode=" + entity.getPageCode() + "; PointCode=" + entity.getBuryingPointCode());
                        return ReqResult.ok("");
                    } else {
                        // return TaskResult.error(JsonParser.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

}
